package com.gohome.gohomechat.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.easemob.chat.EMChat;
import com.easemob.chat.EMContactListener;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMMessage;
import com.gohome.gohomechat.GoHomeHelper;
import com.gohome.gohomechat.R;
import com.gohome.gohomechat.model.entify.ChatType;
import com.gohome.gohomechat.model.entify.Contant;
import com.gohome.gohomechat.model.entify.Friend;
import com.gohome.gohomechat.model.entify.Notice;
import com.gohome.gohomechat.presenter.AddressPresenter;
import com.gohome.gohomechat.presenter.presenterlistener.AddressPresenterInterface;
import com.gohome.gohomechat.ui.activity.ChatActivity;
import com.gohome.gohomechat.ui.activity.GroupChatActivity;
import com.gohome.gohomechat.ui.activity.NoticeActivity;
import com.gohome.gohomechat.ui.adapter.AddressListViewAdapter;
import com.gohome.gohomechat.ui.viewlistener.AddressViewInterface;
import com.gohome.gohomechat.utils.ToActivityUtil;
import com.gohome.gohomechat.utils.ToastUtil;
import com.gohome.gohomechat.view.QuickIndexView;

import java.util.List;

/**
 * Created by dllo on 16/3/1.
 */
public class AddressFragment extends BaseFragment implements QuickIndexView.OnIndexChangedListener, AddressViewInterface, AdapterView.OnItemClickListener {
    private AddressListViewAdapter adapter;
    private ListView listView;
    private QuickIndexView quickIndexView;
    private TextView address_word;
    private List<Friend> datas;
    private AddressPresenterInterface addressPresenterInterface;
    public ImageView address_listview_header_hint;
    private String[] actions = {Contant.ACTION_CONTACT_CHANAGED,
            Contant.ACTION_CONTACT_REFUSED, Contant.NEW_FRIENDS_INVITATION, Contant.NEW_FRIENDS_ADD, Contant.ACCOUNT_REMOVED};

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 100:
                    //隐藏word
                    address_word.setVisibility(View.GONE);
                    break;
            }

            return false;
        }
    });


    @Override
    protected int getLayout() {
        return R.layout.fragment_address;
    }

    @Override
    protected void initPresenter() {
        this.addressPresenterInterface = new AddressPresenter(this);
    }

    @Override
    protected void initView(View view) {
        listView = (ListView) view.findViewById(R.id.address_listview);
        quickIndexView = (QuickIndexView) view.findViewById(R.id.address_indexview);
        adapter = new AddressListViewAdapter(getActivity());
        address_word = (TextView) view.findViewById(R.id.address_word);

        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
        for (int i = 0; i < actions.length; i++) {
            IntentFilter intentFilter = new IntentFilter(actions[i]);
            localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);
        }
    }

    @Override
    protected void initData() {



        quickIndexView.setOnIndexChangedListener(this);

        View headerVeiw_notive = LayoutInflater.from(getActivity()).inflate(R.layout.address_listview_header_notice, null);
        address_listview_header_hint = (ImageView) headerVeiw_notive.findViewById(R.id.address_listview_header_hint);
        View headerVeiw_groupchat = LayoutInflater.from(getActivity()).inflate(R.layout.address_listview_header_groupchat, null);

        listView.addHeaderView(headerVeiw_notive);
        listView.addHeaderView(headerVeiw_groupchat);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);

        addressPresenterInterface.updateData();
    }

    @Override
    public void onIndexChanged(String word) {
        address_word.setText(word);
        address_word.setVisibility(View.VISIBLE);
        //移除未处理的消息
        handler.removeCallbacksAndMessages(null);
        //发延迟消息
        handler.sendEmptyMessageDelayed(100, 1500);

        //滑动listview
        //查找对应的item
        for (int i = 0; i < datas.size(); i++) {
            String fWord = datas.get(i).getPinyin().substring(0, 1).toUpperCase();
            if (word.equals(fWord)) {
                listView.setSelection(i);
                return;
            }
        }
    }

    @Override
    public void onUp() {

    }

    @Override
    public void refreshData(List<Friend> datas) {
        this.datas = datas;
        adapter.addData(datas);
    }

    @Override
    public void updateData(List<Friend> datas) {
        this.datas = datas;
        adapter.addData(datas);
    }

    @Override
    public void obtainDataFailed() {
        ToastUtil.showToast("好友列表获取失败");
    }

    public void toNoticeActivitySuccess(Bundle bundle) {
        if (address_listview_header_hint.getVisibility() == View.VISIBLE) {
//            Bundle bundle=new Bundle();
//            bundle.putParcelable("newNotice",notice);
            ToActivityUtil.startToActivity(getActivity(), NoticeActivity.class, bundle);
            address_listview_header_hint.setVisibility(View.GONE);
        }
    }

    @Override
    public void toNoticeActivitySuccess() {
        if (address_listview_header_hint.getVisibility() == View.VISIBLE) {
            // toNoticeActivitySuccess(bundle);
            address_listview_header_hint.setVisibility(View.GONE);
        }
        ToActivityUtil.startToActivity(getActivity(), NoticeActivity.class);
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            case 0:
                addressPresenterInterface.toNoticeActivity();
                break;
            case 1:
                ToActivityUtil.startToActivity(getActivity(), GroupChatActivity.class);
                break;
            default:
                Bundle bundle=new Bundle();
                bundle.putParcelable("content", new ChatType(EMMessage.ChatType.Chat, datas.get(position - 2).getUserName()));
                ToActivityUtil.startToActivity(getActivity(), ChatActivity.class, bundle);
                GoHomeHelper.getInstance().readMessage(datas.get(position-2).getUserName());
                break;
        }
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // handler.sendEmptyMessage(300);
            if (!GoHomeHelper.getInstance().isRunningNoticeActivity())
                address_listview_header_hint.setVisibility(View.VISIBLE);
            Log.i("adress 监听", intent.getAction() + "<<->>");

            if (intent.getAction().equals(Contant.NEW_FRIENDS_ADD) || intent.getAction().equals(Contant.ACTION_CONTACT_CHANAGED)
                    || intent.getAction().equals(Contant.ACCOUNT_REMOVED)) {
                Log.i("adress 监听", intent.getAction() + "<<-二进宫->>");
                addressPresenterInterface.updateData();
            }

        }
    };

    @Override
    public void onResume() {
        super.onResume();
    }
}
